#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 2021/9/6 15:56
import os
from flask import Flask


def create_app(test_config=None):
    # 创建并且注册app
    app = Flask(__name__, instance_relative_config=True)
    # 避免出现在上下文之外的bug出现
    with app.app_context():
        app.config.from_mapping(
            SECRET_KEY='dev',
            DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite')
        )

        if test_config is None:
            # 载入实例配置 如果它存在的时候就不是测试
            app.config.from_pyfile('config.py', silent=True)
        else:
            # 载入测试配置
            app.config.from_mapping(test_config)
        try:
            os.makedirs(app.instance_path)
        except OSError:
            pass

        from . import (
            db, auth, blog
        )
        db.init_app(app)
        app.register_blueprint(auth.bp)
        app.register_blueprint(blog.bp)
        app.add_url_rule('/', endpoint='index')
    return app
